package com.cooud.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cooud.order.bean.Order;
import com.cooud.order.properties.OrderProperties;
import com.cooud.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/03/12/20:03
 * @Description:
 */
@Slf4j
@RestController
//@RequestMapping("api/order")
//@RefreshScope // 开启自动刷新
public class OrderController {

    @Autowired
    private OrderService orderService;



    @Autowired
    private OrderProperties orderProperties;

    @GetMapping("/config")
    public String config() {
        return "order.timeout=" + orderProperties.getTimeout()
                + ", order.anto-confirm=" + orderProperties.getAutoConfirm()
                + "order.db-url=" + orderProperties.getDbUrl();
    }


    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order",fallback = "seckillFallback")
    public Order seckill(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(Long userId, Long productId, Throwable e) {
        Order order = new Order();
        order.setId(productId);
        order.setAddress("异常信息：" + e.getClass());
        return order;
    }

    @GetMapping("writeDb")
    public String writeDb() {
        return "write db success......";
    }
    @GetMapping("readDb")
    public String readDb() {
        log.info("read db success......");
        return "read db success......";
    }
}
